package com.mrogrape.notepad.ui.library;

import java.awt.Component;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.swing.Icon;
import javax.swing.JTree;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultTreeCellRenderer;

import com.mrogrape.notepad.resource.Icons;
import com.mrogrape.notepad.ui.editor.ContentType;

/**
 * 节点绘制器。
 * 
 * @author IceSpring
 *
 */
public class LibraryCellRenderer extends DefaultTreeCellRenderer {

	/** serialVersionUID */
	private static final long serialVersionUID = 1L;
	
	private Map<File, Icon> iconMap = new HashMap<File, Icon>();

	@Override
	public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
		super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

		// 如果是库节点
		if(value instanceof LibraryNode){
			Library lib = ((LibraryNode) value).getLibrary();
			this.setIcon(Icons.Small.LIBRARY);
			this.setText(lib.getName());
		}
		// 如果是库内容节点
		else if(value instanceof InclusionNode){
			Inclusion inclu = ((InclusionNode) value).getInclusion();
			this.setText(inclu.getName());
			// 如果是文件
			if(LibraryUtils.isFileInclusion(inclu)){
				File file = new File(inclu.getHref());

				Icon icon = this.iconMap.get(file);
				if(icon!=null){
					this.setIcon(icon);
				}
				// 文件不存在
				else if(!file.exists()){
					this.setIcon(Icons.Small.WARNING);
					this.setText(inclu.getName() + "[Missing]");
				}
				else if(ContentType.JAVA.isFileSupportedFor(file)){
					this.setIcon(Icons.Small.JAVA);
				}
				else if(ContentType.HTML.isFileSupportedFor(file)){
					this.setIcon(Icons.Small.HTML);
				}
				else if(ContentType.XML.isFileSupportedFor(file)){
					this.setIcon(Icons.Small.XML);
				}
				else if(ContentType.SQL.isFileSupportedFor(file)){
					this.setIcon(Icons.Small.SQL);
				}
				// 其他场合使用系统图标
				else{
					icon = FileSystemView.getFileSystemView().getSystemIcon(file);
					this.iconMap.put(file, icon);
					this.setIcon(icon);
				}
			}
			else if(Inclusion.URL.equalsIgnoreCase(inclu.getType())){
				this.setIcon(Icons.Small.BROWSER);
			}
		}
		else{
			this.setIcon(Icons.Small.FOLDER);
		}

		return this;
	}



}
